/**
 * 上海中赢金融信息服务有限公司
 * Copyright (c) 2017-2027 Chinazyjr,Inc.All Rights Reserved.
 */

package com.sys.midware.memcached;

import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sys.midware.assist.utils.Assert;
import com.sys.midware.memcached.config.MemcachedConfig;
import com.sys.midware.memcached.config.MemcachedConfigUtil;
import com.sys.midware.memcached.exceptions.BMemcachedException;

import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.MemcachedClientBuilder;
import net.rubyeye.xmemcached.XMemcachedClientBuilder;
import net.rubyeye.xmemcached.command.BinaryCommandFactory;
import net.rubyeye.xmemcached.impl.KetamaMemcachedSessionLocator;
import net.rubyeye.xmemcached.utils.AddrUtil;

/**
 * memcached client封装 <b>ClassName:</b> MemcachedClient.java <br/>
 * <b>Description:</b> TODO <br/>
 * <b>Date:</b> 2015年10月21日 下午4:45:39<br/>
 * 
 * @author mobing
 * @version
 */
public class BMemcachedClient {
    private static final Logger logger = LoggerFactory.getLogger(BMemcachedClient.class);

    // xmemcached
    private MemcachedClient memcachedClient;
    //memcached配置
    private MemcachedConfig mmc;

    public BMemcachedClient() throws Exception {
        mmc = MemcachedConfigUtil.initConfig();
        init();
    }

    private void init() throws Exception {
        logger.info("memcached init begin ..");
        String server = this.mmc.getServers();
        Assert.notNull(server);
        MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses(server));
        builder.setSessionLocator(new KetamaMemcachedSessionLocator());
        builder.setCommandFactory(new BinaryCommandFactory());
        if (this.mmc.getTimeout() >= 0) {
            builder.setConnectTimeout(this.mmc.getTimeout());
        }
        this.memcachedClient = builder.build();
        this.memcachedClient.setTimeoutExceptionThreshold(2147483647);
        logger.info("memcached init finish!");
    }

    public boolean put(String key, Object value, int expiredTimeInSeconds) throws BMemcachedException {
        Assert.notNull(key);
        Assert.notNull(value);
        Assert.notNegative(Integer.valueOf(expiredTimeInSeconds));
        try {
            return this.memcachedClient.set(key, expiredTimeInSeconds, value);
        } catch (Exception e) {
            throw new BMemcachedException(e);

        }
    }

    public boolean put(String key, Object value) throws BMemcachedException {
        return put(key, value, this.mmc.getExpiretime());
    }

    public boolean remove(String key) throws Exception {
        Assert.notNull(key);
        return this.memcachedClient.delete(key);
    }

    public void remove(Set<String> keys) throws BMemcachedException {
        Assert.notNull(keys);
        try {
            for (String key : keys) {
                this.memcachedClient.deleteWithNoReply(key);
            }
        } catch (Exception e) {
            throw new BMemcachedException(e);
        }
    }

    public <T> T get(String key) throws BMemcachedException {
        Assert.notNull(key);
        try {
            return this.memcachedClient.get(key);
        } catch (Exception e) {
            throw new BMemcachedException(e);

        }
    }

    public void put(Map<? extends Object, ? extends Object> map) throws Exception {
        put(map, this.mmc.getExpiretime());
    }

    public void put(Map<? extends Object, ? extends Object> map, int expiredTimeInSeconds) throws Exception {
        Assert.notNull(map);
        if (map.isEmpty()) {
            return;
        }
        for (Map.Entry entry : map.entrySet()) {
            Object key = entry.getKey();
            Object value = entry.getValue();
            if ((key == null) || (value == null)) {
                continue;
            }
            this.memcachedClient.setWithNoReply(key.toString(), expiredTimeInSeconds, value);
        }
    }

    public void shutDown() throws Exception {
        this.memcachedClient.shutdown();
    }

    public static void main(String[] args) throws Exception {

        BMemcachedClient bmmc = new BMemcachedClient();
        bmmc.put("mobing", "123456");
        System.out.println("---" + bmmc.get("mobing"));
    }
}
